package com.sinoglobal.sinostore.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.PayTask;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;
import com.sinoglobal.sinostore.R;
import com.sinoglobal.sinostore.StateBaseActivity;
import com.sinoglobal.sinostore.bean.ParforVo;
import com.sinoglobal.sinostore.dialog.SweetAlertDialog;
import com.sinoglobal.sinostore.dialog.SweetAlertDialog.OnSweetClickListener;
import com.sinoglobal.sinostore.system.Constants;
import com.sinoglobal.sinostore.utils.ApiDebugUtil;
import com.sinoglobal.sinostore.utils.Result;
import com.sinoglobal.sinostore.utils.SignUtil;
import com.umpay.quickpay.UmpPayInfoBean;
import com.umpay.quickpay.UmpayQuickPay;
/**
 * 
* @title: PayforActivity.java 
* @package com.chiliring.sinostore.activity 
* @description: TODO(支付页面) 
* @author LK
* @date 2015-1-16 下午4:13:45
 */
public class PayforActivity extends StateBaseActivity implements OnClickListener,OnCheckedChangeListener {
	public static final String PARTNER = "";
	public static final String SELLER = "";
	public static final String RSA_PRIVATE = "";
	public static final String RSA_PUBLIC = "";
	
	/**请求返回码**/
	public static final int REQUESTCODE = 1;
	
	private static final int SDK_PAY_FLAG = 1;

	private static final int SDK_CHECK_FLAG = 2;
	
	/**优付支付成功**/
	private static final String UMPAY_SUCCESS = "0000";
	/**优付支付取消**/
	private static final String UMPAY_CANCEL = "1001";
	
	/**立即支付**/
//	@ViewInject(R.id.btn_payfor)
	private TextView btnPayFor;
	
	private String goodsName;
	/**支付方式**/
	private int payType = 0;
	
	/**现金或者积分支付**/
	private int scoreOrMoney;
	
	/**现金支付**/
//	@ViewInject(R.id.ll_money_pay)
	private LinearLayout llMoneyPay;
	/**积分支付**/
//	@ViewInject(R.id.tv_score_pay)
	private RelativeLayout tvScorePay;
	/**订单编号**/
	private String orderNum;
	/**1自取2快递**/
	private static String submitType;
	/**商品类型**/
	private static String goodsType;
	/**领取时间**/
	private static String validDate;
	/**商品图片**/
	private static String goodsImg;
	
	/**支付宝**/
//	@ViewInject(R.id.cb_alipay)
	private CheckBox cbAliPay;
	
	/**积分支付**/
//	@ViewInject(R.id.cb_scorepay)
	private CheckBox cbScorePay;
	
	/**优付支付**/
//	@ViewInject(R.id.cb_umpay)
	private CheckBox cbUmPay;
	
	/**支付页面**/
//	@ViewInject(R.id.ll_pay)
	private LinearLayout llPay;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shop_activity_payfor);
		openChenJInShi();
		titleView.setText("确认支付");
//		ViewUtils.inject(this);
		
		initView();
		
		initData();
	}
	
	private void initView(){
		btnPayFor=getViewById(R.id.btn_payfor);
		llMoneyPay=getViewById(R.id.ll_money_pay);
		tvScorePay=getViewById(R.id.tv_score_pay);
		cbAliPay=getViewById(R.id.cb_alipay);
		cbScorePay=getViewById(R.id.cb_scorepay);
		cbUmPay=getViewById(R.id.cb_umpay);
		llPay=getViewById(R.id.ll_pay);
		
		
		btnPayFor.setOnClickListener(this);
		templateButtonLeft.setOnClickListener(this);
		cbAliPay.setOnCheckedChangeListener(this);
		cbScorePay.setOnCheckedChangeListener(this);
		cbUmPay.setOnCheckedChangeListener(this);
		btnPayFor.setClickable(false);
		llPay.setVisibility(View.INVISIBLE);
	}
	
	private void initData(){
		goodsType = getIntent().getStringExtra("goodsType");
		orderNum = getIntent().getStringExtra("orderNum");
		goodsName = getIntent().getStringExtra("goodsName");
		submitType = getIntent().getStringExtra("submitType");
		scoreOrMoney = getIntent().getIntExtra("payType",0);
		goodsImg = getIntent().getStringExtra("goodsImg");
		if(TextUtils.isEmpty(orderNum)){
			showShortToast("订单支付失败");
			new Handler().postDelayed(new Runnable() {
				
				@Override
				public void run() {
					PayforActivity.this.finish();
				}
			}, 2000);
		}
		//选择支付方式
		switch (scoreOrMoney) {
		//积分支付
		case Constants.SCOREPAY:
			llMoneyPay.setVisibility(View.GONE);
			tvScorePay.setVisibility(View.VISIBLE);
			payType = Constants.SCOREPAY;
			llPay.setVisibility(View.VISIBLE);
			break;
		//现金支付
		case Constants.MONEYPAY:
			llMoneyPay.setVisibility(View.VISIBLE);
			tvScorePay.setVisibility(View.GONE);
			llPay.setVisibility(View.VISIBLE);
			break;
		default:
			showShortToast("选取支付方式失败，请前往我的订单中重新支付");
			break;
		}
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.btn_payfor) {
			if(payType == 0){
				showShortToast("请选择支付方式");
				return;
			}
			payfor();
		} else if (id == R.id.shop_title_but_left) {
			cancelOrder();
		} else {
		}
	}
	
	//取消订单
		private void cancelOrder(){
			final SweetAlertDialog alertDialog = new SweetAlertDialog(PayforActivity.this);
			alertDialog.showCancelButton(true);
			alertDialog.setTitleText("确认放弃支付？");
			alertDialog.setContentText("");
			alertDialog.setCancelText("取消");
			alertDialog.setConfirmText("确定");
			alertDialog.setConfirmClickListener(new OnSweetClickListener() {
				@Override
				public void onClick(SweetAlertDialog sweetAlertDialog) {
					alertDialog.dismiss();
					PayforActivity.this.finish();
				}
			});
			alertDialog.show();
		}
		
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
			cancelOrder();
			return true;
        }
		return super.onKeyDown(keyCode, event);
	}
	
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				Result resultObj = new Result((String) msg.obj);
				String resultStatus = resultObj.resultStatus;

				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					showShortToast("支付成功");
					Intent intent = new Intent(PayforActivity.this,PayForSuccessActivity.class);
					intent.putExtra("goodsName",goodsName);
					intent.putExtra("goodsType", goodsType);
					intent.putExtra("submitType", submitType);
					intent.putExtra("validDate", validDate);
					intent.putExtra("goodsImg", goodsImg);
					startActivity(intent);
					overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
					PayforActivity.this.finish();
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000” 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						showShortToast("支付结果确认中");
					} else {
						showShortToast("支付失败");
					}
				}
				break;
			}
			case SDK_CHECK_FLAG: {
				showShortToast("检查结果为：" + msg.obj);
				
				break;
			}
			default:
				break;
			}
		};
	};
	
	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public void pay(final String orderInfo) {
		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(PayforActivity.this);
				// 调用支付接口
				String result = alipay.pay(orderInfo);
				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}
	
	/**
	 * 
	* @author LK
	* @methods payfor 
	* @description 描述信息 支付
	* @date 2015-1-22 下午2:02:03 参数说明
	 */
	private void payfor(){
		final ProgressDialog dialog = new ProgressDialog(this);
		try {
			dialog.show();
		} catch (Exception e) {
		}
		HttpUtils httpUtils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("proIden",Constants.STOREFLAG);
		params.addQueryStringParameter("por","204");
		params.addQueryStringParameter("order_num",orderNum);
		params.addQueryStringParameter("user_id", Constants.userCenterId);
		params.addQueryStringParameter("pay_type", String.valueOf(payType));
		params.addQueryStringParameter("sign", SignUtil.generateSign(params));
		ApiDebugUtil.debug(params);
		httpUtils.send(HttpMethod.POST, Constants.STORE_URL, params ,new RequestCallBack<String>() {

			@Override
			public void onStart() {
				super.onStart();
				LogUtils.i("RESULT ==="+this.getRequestUrl());
			}
			@Override
			public void onFailure(HttpException arg0, String arg1){
				showShortToast("订单支付失败");
				try {
					dialog.dismiss();
				} catch (Exception e) {
				}
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				try {
					dialog.dismiss();
				} catch (Exception e) {
				}
				String result = responseInfo.result;
				LogUtils.e("result=="+result);
				
				if(!TextUtils.isEmpty(result)){
					ParforVo entity;
					try {
						entity = JSON.parseObject(result, ParforVo.class);
					} catch (Exception e) {
						e.printStackTrace();
						showShortToast("系统正在维护中");
						return;
					}
					if(null != entity){
						if(Constants.STORE_SUCCESS_CODE.equals(entity.getCode())){
							validDate = entity.getValid_date();
							if(payType == Constants.ALIPAY){
								//调用支付宝
								pay(entity.getOrderInfor());
							}else if(payType == Constants.SCOREPAY){
								showShortToast("支付成功");
								Intent intent = new Intent(PayforActivity.this,PayForSuccessActivity.class);
								intent.putExtra("goodsName",goodsName);
								intent.putExtra("goodsType", goodsType);
								intent.putExtra("submitType", submitType);
								intent.putExtra("validDate", validDate);
								intent.putExtra("goodsImg", goodsImg);
								startActivity(intent);
								overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
								PayforActivity.this.finish();
							}else if(payType == Constants.UMPAY){
								LogUtils.i(">>>>>>>>>>>>>>>>>>>>>"+entity.getTrade_no());
								UmpayQuickPay.requestPayWithBind(PayforActivity.this, entity.getTrade_no(), null,
			                            null, null, new UmpPayInfoBean(), REQUESTCODE);
							}
						}else if(Constants.STORE_TIMEOUT.equals(entity.getCode())){
							showShortToast("支付超时，订单已被关闭");
							new Handler().postDelayed(new Runnable() {
								@Override
								public void run() {
									toActivity(OrderListActivity.class, null);
									PayforActivity.this.finish();
								}
							}, 2000);
						}else if(Constants.STORE_SORCENOTMORE.equals(entity.getCode())){//积分不足
							showShortToast(getString(R.string.outofcash));
						}else{
							showShortToast(entity.getMessage());
						}
						}
					}
				}
		});
	}
	
	
	/**
     * 3.在这里接收并处理支付结果
     * 
     * @param requestCode 支付请求码
     * @param resultCode SDK固定返回88888
     * @param data 支付结果和结果描述信息
     * @author niexuyang 2012-8-20
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUESTCODE) {
        	String umpresultCode = data.getStringExtra("umpResultCode");
           if(UMPAY_SUCCESS.equals(umpresultCode)){
        	   showShortToast("支付成功");
				Intent intent = new Intent(PayforActivity.this,PayForSuccessActivity.class);
				intent.putExtra("goodsName",goodsName);
				intent.putExtra("goodsType", goodsType);
				intent.putExtra("submitType", submitType);
				intent.putExtra("validDate", validDate);
				intent.putExtra("goodsImg", goodsImg);
				startActivity(intent);
				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
				PayforActivity.this.finish();
           }else if(UMPAY_CANCEL.equals(umpresultCode)){
        	   showShortToast("取消支付");
           }else{
        	   showShortToast("支付失败");
           }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
	

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		int id = buttonView.getId();
		if (id == R.id.cb_alipay) {
			if(cbAliPay.isChecked()){
				payType = Constants.ALIPAY;
				cbUmPay.setChecked(false);
			}
		} else if (id == R.id.cb_scorepay) {
			if(cbScorePay.isChecked()){
				payType = Constants.SCOREPAY;
			}
		} else if (id == R.id.cb_umpay) {
			if(cbUmPay.isChecked()){
				payType = Constants.UMPAY;
				cbAliPay.setChecked(false);
			}
		} else {
		}
		if(buttonView.isChecked()){
			btnPayFor.setBackgroundDrawable(getResources().getDrawable(R.drawable.shop_mall_content_btn_selected));
			btnPayFor.setTextColor(getResources().getColor(R.color.white));
			btnPayFor.setClickable(true);
		}else{
			btnPayFor.setBackgroundDrawable(getResources().getDrawable(R.drawable.shop_mall_content_btn_normal));
			btnPayFor.setTextColor(getResources().getColor(R.color.textBlack));
			btnPayFor.setClickable(false);
		}
	}
}
